<template>
	<view class="article">
		<unicloud-db v-slot:default="{data, loading, error, options}" collection="wolf-activity" :where="where"
			:getone="true" :manual="true" ref="detail" @load="loadData">
			<template v-if="!loading && data">
				<view class="banner">
					<!-- 文章开头，缩略图 -->
					<image class="banner-img" :src="data.icon" mode="widthFix"></image>
					<!-- 文章摘要 -->
					<view class="banner-title">
						<text class="uni-ellipsis">{{data.title}}</text>
					</view>
				</view>
				<view class="article-content">
					<rich-text :nodes="data.des"></rich-text>
				</view>
				<view class="bottom">
					<view class="b-price">￥<text class="b-title">{{data.price/100 || 0}}</text></view>
					<view class="b-btn" @click="pay">支付</view>
				</view>
			</template>
		</unicloud-db>
		<uni-pay ref="uniPay" :to-success-page="false" @success="onSuccess"></uni-pay>
	</view>
</template>

<script>
	import {
		mapState
	} from "pinia";
	import {
		useUserStore
	} from "@/pinia/user.js";
	// const user = uniCloud.importObject('two-plus-one')
	const db = uniCloud.database();
	export default {
		data() {
			return {
				id: '',
				price: 0,
				num:0
			}
		},
		onLoad(event) {
			//获取真实id，通常 id 来自上一个页面
			if (event.id) {
				this.id = event.id
			}
			//若上一页传递了标题过来，则设置导航栏标题
			if (event.title) {
				this.title = event.title
				uni.setNavigationBarTitle({
					title: event.title
				})
			}
		},
		computed: {
			...mapState(useUserStore, ['userInfo', 'updateUserInfo']),
			where() {
				return `_id =="${this.id}"`
			}
		},
		onReady() {
			// 开始加载数据，修改 where 条件后才开始去加载 clinetDB 的数据 ，需要等组件渲染完毕后才开始执行 loadData，所以不能再 onLoad 中执行
			if (this.id) { // ID 不为空，则发起查询
				this.$refs.detail.loadData()
			} else {
				uni.showToast({
					icon: 'none',
					title: this.$t('listDetail.newsErr')
				})
			}
		},
		methods: {
			loadData(data) {
				console.log("ddddd", data)
				this.price = data.price || 0
				this.num = data.num || 0
				if (this.title == '' && data.title) {
					this.title = data.title
					uni.setNavigationBarTitle({
						title: data.title
					});
				}
			},
			async pay() {
				let now = new Date().getTime() //获取当前时间戳
				let code = '' + (parseInt(Math.random() * 1000000) + 1000000)
				code = code.substring(1, 7)
				let order_no = "ACT" + code + now //业务订单号
				let type = this.id
				let obj = {
					order_no, //订单编号
					uid: this.userInfo._id, //购买人
					price: this.price,
					status: 0,
					type,
					num:this.num
				}
				// console.log('oRes', obj)
				// return
				let oRes = await db.collection('wolf-pay-order').add(obj)
				console.log('oRes', oRes)
				if (oRes.result.id) {
					let out_trade_no = `${order_no}-1`; // 生成插件支付单号
					let description = "产品购买"
					// 打开支付收银台
					let payRes = await this.$refs.uniPay.open({
						total_fee: this.price, // 支付金额，单位分 100 = 1元
						order_no: order_no, // 业务系统订单号（即你自己业务系统的订单表的订单号）
						out_trade_no: out_trade_no, // 插件支付单号
						description, // 支付描述
						type: 'setProfitSharing', // 支付回调类型
						custom: obj, // 自定义数据
					});
					console.log("payRes",payRes)
					// let res = await user.setProfitSharing({
					// 	id: this.userInfo._id,
					// 	orderid: order_no,
					// 	price: this.price
					// })
					// console.log("res++", res)
					// this.updateUserInfo()
				}
				console.log("pay")
			},
			// 监听事件 - 支付成功
			onSuccess(res) {
				console.log('success: ', res);
				if (res.user_order_success) {
					// 代表用户已付款，且你自己写的回调成功并正确执行了
					uni.showToast({
						title: "购买成功",
						icon: "none"
					})
					this.updateUserInfo()
					// uni.redirectTo({
					// 	url: `/uni_modules/uni-pay/pages/success/success?out_trade_no=${res.out_trade_no}&order_no=${res.pay_order.order_no}&pay_date=${res.pay_order.pay_date}&total_fee=${res.pay_order.total_fee}&adpid=${this.adpid}&return_url=${this.return_url}&main_color=${this.main_color}`
					// });
				} else {
					// 代表用户已付款，但你自己写的回调执行成功（通常是因为你的回调代码有问题）
			
				}
			},
		}
	}
</script>

<style scoped lang="scss">
	.banner {
		position: relative;
		margin: 0 15px;
		height: 180px;
		overflow: hidden;
	}

	.banner-img {
		position: absolute;
		width: 100%;
	}

	.banner-title {
		display: flex;
		align-items: center;
		position: absolute;
		padding: 0 15px;
		width: 100%;
		bottom: 0;
		height: 30px;
		font-size: 14px;
		color: #fff;
		background: rgba(0, 0, 0, 0.4);
		overflow: hidden;
		box-sizing: border-box;
	}

	.uni-ellipsis {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.article-content {
		padding: 15px;
		font-size: 15px;
		overflow: hidden;
		margin-bottom: 40px;
	}

	.bottom {
		display: flex;
		position: fixed;
		align-items: center;
		bottom: 0;
		height: 40px;
		width: 100%;
		background-color: #fff;
		padding: 0 15px;
	}

	.b-price {
		flex: 1;
	}

	.b-btn {
		width: 200px;
		background-color: #ff0000;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #fff;
		border-top-left-radius: 5px;
	}

	.b-title {
		font-size: 22px;
		font-weight: 700;
		color: #079400;
	}
</style>